package com.twinkle.blockchain.merkle;

import cn.hutool.crypto.digest.DigestUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 默克尔树的实现
 */
public class MerkleTree {
    /**
     *  交易列表
     */
    private List<String> txList;
    /**
     *  默克尔树根
     */
    private String root;

    public MerkleTree(List<String> txList) {
        this.txList = txList;
        root = "";
    }

    /**
     * 构造Merkel哈希树
     * @return
     */
    public MerkleTree buildMerkleTree() {
        List<String> tempTxList = new ArrayList<>(this.txList);

        List<String> newTxList = getNewTxList(tempTxList);
        if (newTxList.size() != 1) {
            newTxList = getNewTxList(newTxList);
        }
        this.root = newTxList.get(0);
        return this;
    }

    private List<String> getNewTxList(List<String> tempTxList) {
        List<String> newTxList = new ArrayList<>();
        int index = 0;
        while (index < tempTxList.size()) {
            String leftTx = tempTxList.get(index);
            index++;
            String rightTx = "";
            if (index < tempTxList.size()) {
                rightTx = tempTxList.get(index);
            }
            newTxList.add(DigestUtil.sha256Hex(leftTx+rightTx));
            index++;
        }
        return newTxList;
    }

    public String getRoot() {
        return this.root;
    }
}
